package genedit.controller.interfaceActions;

import genedit.gui.GFileChooser;
import genedit.gui.GMainFrame;
import genedit.model.Project;
import genedit.model.Workspace;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;

/**
 * Akcija za sačuvavanje svih otvorenih projekata.
 * 
 * @author Nikola
 * @version 1.0 5/11/12
 */
public class GSaveAllA extends AbstractAction {
	private static final long serialVersionUID = 1L;

	private static GSaveAllA instance = null;

	public static GSaveAllA getInstance() {
		if (instance == null)
			instance = new GSaveAllA();
		return instance;
	}

	private GSaveAllA() {
		putValue(NAME, "Save All");
		putValue(SMALL_ICON, new ImageIcon("resources/icons/save_all.png"));
		putValue(MNEMONIC_KEY, KeyEvent.VK_V);
		putValue(
				ACCELERATOR_KEY,
				KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK
						| ActionEvent.SHIFT_MASK));
		putValue(SHORT_DESCRIPTION, "Save All");
	}

	/**
	 * Akcija poziva operaciju Save na sve projekte koji su već postojali na
	 * hard disku i Save As za novokreirane projekte, koji još nisu imali
	 * priliku da se sačuvaju.
	 * 
	 * @see GSaveA, GSaveAsA
	 */
	public void actionPerformed(ActionEvent arg0) {
		List<Project> projekti = Workspace.getInstance().getProjects();
		for (Project p : projekti) {
			if (p.getPath() == null) {
				if (GFileChooser.getInstance(false).showSaveDialog(GMainFrame.getInstance()) == JFileChooser.APPROVE_OPTION) {
					File fileName = new File(GFileChooser.getInstance(false).getSelectedFile()
							+ ".proj");

					if (fileName.exists()) {
						if (JOptionPane.showConfirmDialog(null, "Replace existing file?",
								"Overwrite file", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION)
							continue;
					}

					try {
						p.setPath(fileName.getCanonicalPath());
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				} else
					continue;
			}

			try {
				ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(p.getPath()));
				out.writeObject(p);
				out.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}